<template>
  <div id="Shenghuohui">
    <div id="shenghuohuiDetail">
      <el-dialog title="查看" :visible.sync="dialogVisible" width="50%" top="20px" :close-on-click-modal="false" :close-on-press-escape="false" append-to-body>
        <el-timeline>
          <el-timeline-item
            v-for="(activity, index) in activities"
            :key="index"
            :icon="activity.icon"
            :type="activity.type"
            :timestamp="activity.operateTime">
            {{activity.content}}
          </el-timeline-item>
        </el-timeline>
      </el-dialog>
      <el-dialog title="退回" :visible.sync="backDialogVisible" width="50%" top="20px" :close-on-click-modal="false" :close-on-press-escape="false" append-to-body>
        <el-form ref="backForm" :model="backForm" class="form-container" label-width="100px" :rules="rules">
          <el-form-item prop="remark" label="退回原因">
            <el-input v-model.trim="backForm.remark" style="width:600px" />
          </el-form-item>
          <el-form-item>
            <el-button type="danger" :loading="loading" @click="submitBack">退回</el-button>
          </el-form-item>
        </el-form>
      </el-dialog>
      <el-breadcrumb separator=">">
        <el-breadcrumb-item :to="{ path: '/' }">系统首页</el-breadcrumb-item>
        <el-breadcrumb-item :to="{ name: 'Shenghuohui' }">民主生活会</el-breadcrumb-item>
        <el-breadcrumb-item>{{shenghuohuiName}}</el-breadcrumb-item>
      </el-breadcrumb>
      <section>
      <div id="listtree" class="wboxd" :style="'height:'+tableHeight+'px'">
        <el-scrollbar style="height:calc(100% + 25px);">
          <!-- <el-button style="float:right; margin-left:10px;" :disabled="!canExport" type="success" size="small" @click.native="exportexcel" :loading="exportloading">导出民主生活会评估表</el-button> -->
          <el-button :disabled="!pingguFiles" style="float:right; margin-left:10px;" type="primary" size="small" @click.native="exportexcelfujian" :loading="exportloading">导出手动上传的民主生活会评估表</el-button>
          <el-button v-if="TheYear === 2021" style="float:right; margin-left:10px;" :disabled="!canExport" type="success" size="small" @click.native="exportexcel" :loading="exportloading">导出系统生成的民主生活会评估表</el-button>
          <el-button v-if="inRoles('ROLE_shhadmin')" style="float:right; margin-left:10px;" type="primary" size="small" @click.native="exportexcelnew" :loading="exportloading">导出民主生活会会议情况</el-button>
          <template v-if="TheYear>=2021 && inRoles('ROLE_shhadmin')">
            <el-button v-if="showExpertBtn" style="float:right; margin-left:10px;" type="success" size="small" @click.native="exportAll('生成')" :loading="exportloading">生成全部单位民主生活会材料导出文件</el-button>
            <span v-if="showLoading" style="float:right; margin-left:10px; line-height: 36px;">
              <i class="el-icon-loading"></i>
              目前已经生成{{ loadingFileCount }}文件
            </span>
            <el-button v-if="showDownloadBtn" style="float:right; margin-left:10px;" type="success" size="small" @click.native="downloadAll" :loading="exportloading">下载全部单位民主生活会材料导出文件</el-button>
            <el-button v-if="showResetBtn" style="float:right; margin-left:10px;" type="danger" size="small" @click.native="exportAll('重新生成', true)" :loading="exportloading">重新生成全部单位民主生活会材料导出文件</el-button>
            <el-tooltip v-if="showResetBtn && expertFailReason" style="float:right; margin-left:10px; line-height: 36px;" effect="dark" :content="expertFailReason" placement="bottom">
              <span>失败原因<i class="el-icon-question"></i></span>
            </el-tooltip>
          </template>
          <el-input placeholder="输入关键字进行过滤" v-model="filterText" style="width:400px;"></el-input>
          <el-tree node-key="name" :expand-on-click-node="false" :render-content="renderContent" class="filter-tree" :data="deptlist" :filter-node-method="filterNode" ref="tree2" :empty-text="loadingtext"></el-tree>
        </el-scrollbar>
      </div>
        <!--新增界面-->
      </section>
    </div>
  </div>
</template>

<script>
export default {
  watch: {
    filterText (val) {
      this.$refs.tree2.filter(val)
    }
  },
  data () {
    const validateRequire = (rule, value, callback) => {
      if (value === null || value === undefined || value === '') {
        callback(new Error('必填项'))
      } else {
        callback()
      }
    }
    return {
      status: null,
      TheYear: '',
      canCreate: false,
      pingguFiles: false,
      loading: false,
      rules: {
        remark: [{ validator: validateRequire }]
      },
      backDialogVisible: false,
      backForm: {
        remark: ''
      },
      activities: [],
      dialogVisible: false,
      loadingtext: '正在加载...',
      tableHeight: 0,
      shhAuth: 0,
      filterText: '',
      deptlist: [],
      listLoading: false,
      totalnum: 0,
      startBtnsVisible: false,
      startLoading: false,
      Sortkey: '',
      Isace: true,
      shenghuohuiName: '',
      exportloading: false,
      canExport: false,
      shenghuohuiunitId: 0,
      showExpertBtn: true,
      showLoading: false,
      loadingFileCount: 0,
      showDownloadBtn: false,
      showResetBtn: false,
      expertFailReason: ''
    }
  },
  methods: {
    exportAll (msg, flag) {
      this.$confirm(`确认要${msg}吗?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.loadingFileCount = 0
        this.expertFailReason = ''
        this.exportloading = true
        let url = this.$http.defaults.shenghuohuiAPI + `api/shenghuohui/buildShhZip?shenghuohuiId=` + this.$route.params.id
        if (flag) {
          url += '&deleteFlag=' + flag
        }
        this.$http
          .get(url)
          .then(response => {
            this.exportloading = false
            if (response.data.success === true) {
              const result = response.data.result
              if (result.status === 1) {
                this.$message({
                  message: '该生活会导出文件正在生成中',
                  type: 'info'
                })
                this.queryProgress()
              } else if (result.status === 2) {
                this.$message({
                  message: `该生活会导出文件已由用户${result.createUserName}于${result.finishTime}生成成功`,
                  type: 'success'
                })
                this.showBtnHandler(['showDownloadBtn', 'showResetBtn'])
              } else if (result.status === 3) {
                this.$message({
                  message: `该生活会导出文件已由用户${result.createUserName}于${result.finishTime}生成失败`,
                  type: 'error'
                })
                this.showBtnHandler(['showResetBtn'])
                this.expertFailReason = result.failReason
              }
            } else {
              console.log('获取失败:' + response.data.message)
              this.$message({
                message: '获取失败:' + response.data.message,
                type: 'error'
              })
            }
          })
          .catch(error => {
            console.log(error)
            this.$message({
              message: '获取失败:' + error,
              type: 'error'
            })
            this.exportloading = false
          })
      })
    },
    queryProgress () {
      if (this.$route.params.id) {
        this.$http
          .get(this.$http.defaults.shenghuohuiAPI + `api/shenghuohui/getShhExport?shenghuohuiId=` + this.$route.params.id)
          .then(response => {
            if (response.data.success === true) {
              const result = response.data.result
              if (result.status === 1) {
                this.showBtnHandler(['showLoading'])
                this.loadingFileCount = result.fileNum
                setTimeout(() => {
                  if (this.$route.params.id) {
                    this.queryProgress()
                  }
                }, 500)
              } else if (result.status === 2) {
                this.$message({
                  message: `生成成功`,
                  type: 'success'
                })
                this.showBtnHandler(['showDownloadBtn', 'showResetBtn'])
              } else if (result.status === 3) {
                this.$message({
                  message: `生成失败`,
                  type: 'error'
                })
                this.showBtnHandler(['showResetBtn'])
                this.expertFailReason = result.failReason
              }
            } else {
              console.log('获取失败:' + response.data.message)
              this.$message({
                message: '获取失败:' + response.data.message,
                type: 'error'
              })
            }
          })
          .catch(error => {
            console.log(error)
            this.$message({
              message: '获取失败:' + error,
              type: 'error'
            })
          })
      }
    },
    downloadAll () {
      window.open(this.$http.defaults.baseURL + this.$http.defaults.shenghuohuiAPI + `api/shenghuohui/downloadShhZip?shenghuohuiId=` + this.$route.params.id)
    },
    showBtnHandler (flagArr) {
      this.showExpertBtn = false
      this.showLoading = false
      this.showDownloadBtn = false
      this.showResetBtn = false
      flagArr.forEach(item => {
        this[item] = true
      })
    },
    filterNode (value, data) {
      console.log('val:' + value)
      if (!value) return true
      return data.unitName.indexOf(value) !== -1
    },
    renderContent (h, { node, data, store }) {
      console.log('node')
      console.log(node)
      console.log(data)
      console.log(store)
      return (
        <div class="nodelist" style="width:100%;height:50px;" title={data.title} >
          <div style={data.depttype === '分类' ? 'font-weight:bolder;float:right' : 'float:right'}>
            <div ref="EditBtns" style="float:right;height:50px;padding:0 10px;width:200px;">
              <el-button size="small" on-click={ () => this.unitshow(data.shenghuohuiunitId, data.flag) } type="primary" v-show={data.depttype !== '分类' && data.flowType === 2}>详情</el-button>
              <el-button size="small" on-click={ () => this.flowback(data.shenghuohuiunitId) } type="danger" v-show={data.depttype !== '分类' && data.flowType === 2 && this.status === 1 && (this.shhAuth === '2' || this.inRoles('ROLE_shhadmin') || this.inRoles('ROLE_admin'))}>退回</el-button>
            </div>
            <div style="float:right;line-height:28px;padding:11px 10px 0;width:350px" class="Dangqianzhuangtai">
              <span style="color:red;font-weight:bolder" v-show={data.flowType === 3}>已退回</span>
              <span style="color:green;font-weight:bolder" v-show={data.flowType === 2}>已提交</span>
              <span v-show={data.flowType === 1}>已启动</span>
              <span v-show={data.depttype === '分类'}>状态</span>
              <el-button icon="el-icon-search" style="margin-left:10px;" type="text" size="small" on-click={ () => this.flowshow(data.shenghuohuiunitId) } v-show={data.depttype !== '分类' && (this.shhAuth === 2 || this.inRoles('ROLE_shhadmin') || this.inRoles('ROLE_admin'))}></el-button><el-tooltip v-show={data.zhiliangpinggu} class="item" effect="dark" content="已生成质量评估" placement="top">
                <i class="el-icon-s-flag" style="color:green;margin-right:10px" />
              </el-tooltip>
            </div>
          </div>
          <i class={data.depttype === '分类' ? 'icon-wenjianjia1 tree-icon iconfont' : 'icon-danwei tree-icon iconfont'} style="float:left" />
          <span title={data.unitName} style={data.depttype === '分类' ? 'font-weight:bolder;line-height:28px' : 'line-height: 50px;display:block;text-overflow:ellipsis;width:600px;overflow:hidden;float:left;'}>{data.unitName}</span>
        </div>
      )
    },
    flowback (id) {
      this.backDialogVisible = true
      this.backForm.remark = ''
      this.shenghuohuiunitId = id
    },
    submitBack (id) {
      this.$refs.backForm.validate((valid) => {
        if (valid) {
          this.loading = true
          this.$http
            .post(this.$http.defaults.shenghuohuiAPI + `api/newFlow/saveBack`, {shenghuohuiunitId: this.shenghuohuiunitId, remark: this.backForm.remark})
            .then(response => {
              this.loading = false
              if (response.data.success === true) {
                this.$message({
                  message: '退回成功:',
                  type: 'success'
                })
                this.backDialogVisible = false
                this.getDept()
              } else {
                console.log('退回失败:' + response.data.message)
                this.$message({
                  message: '退回失败:' + response.data.message,
                  type: 'error'
                })
              }
            })
            .catch(error => {
              this.loading = false
              console.log(error)
              this.$message({
                message: '退回失败:' + error,
                type: 'error'
              })
            })
        }
      })
    },
    flowshow (id) {
      this.dialogVisible = true
      this.$http
        .post(this.$http.defaults.shenghuohuiAPI + `api/newFlow/queryByPage`, {shenghuohuiunitId: id, pageNum: 1, pageSize: 1000})
        .then(response => {
          if (response.data.success === true) {
            this.activities = response.data.result.records.map(item => {
              let newItem = {}
              switch (item.flowType) {
                case 1:
                  newItem = {operateTime: item.operateTime, content: '启动(' + item.operateUserName + ')', type: 'primary'}
                  break
                case 2:
                  newItem = {operateTime: item.operateTime, content: '提交(' + item.operateUserName + ')', type: 'success'}
                  break
                case 3:
                  newItem = {operateTime: item.operateTime, content: '退回(' + item.operateUserName + ')：' + item.remark, type: 'danger'}
                  break
              }
              return newItem
            })
          } else {
            console.log('获取失败:' + response.data.message)
            this.$message({
              message: '获取失败:' + response.data.message,
              type: 'error'
            })
          }
        })
        .catch(error => {
          console.log(error)
          this.$message({
            message: '获取失败:' + error,
            type: 'error'
          })
        })
    },
    unitshow: function (id) {
      if (this.TheYear === 2018) {
        this.$router.push({name: `shenghuohuiUnit2018`, params: {id: id}})
      } else if (this.TheYear === 2019) {
        this.$router.push({name: `shenghuohuiUnit2019`, params: {id: id}})
      } else if (this.TheYear === 2020) {
        this.$router.push({name: `shenghuohuiUnit2020`, params: {id: id}})
      } else if (this.TheYear === 2021) {
        this.$router.push({name: `shenghuohuiUnit2021`, params: {id: id}})
      } else if (this.TheYear >= 2022) {
        this.$router.push({name: `shenghuohuiUnit2022`, params: {id: id}})
      }
    },
    tableRowClassName (val) {
      if (val.row.Zhuangtai === '未接收') {
        return 'row-b'
      } else {
        return ''
      }
    },
    sortChange: function (column, prop, order) {
      this.Sortkey = column.prop
      if (column.order === 'ascending') {
        this.Isace = true
      } else {
        this.Isace = false
      }
      this.getDept()
    },
    inRoles (str) {
      let arr = JSON.parse(localStorage.getItem('Roles'))
      if (arr.indexOf(str) === -1) {
        return false
      } else {
        return true
      }
    },
    // 获取列表
    getDept () {
      this.loadingtext = '正在加载...'
      this.startBtnsVisible = false
      this.listLoading = true
      // var personParams = { Page: 0, Pagenum: 20, Personname: '', Unitkey: '', Sortkey: '', Isace: true, timestamp: new Date().getTime() }
      this.$http
        .get(this.$http.defaults.shenghuohuiAPI + `api/newFlow/getAllUnits?shenghuohuiId=` + this.$route.params.id)
        .then(response => {
          this.listLoading = false
          if (response.data.success === true) {
            console.log('获取成功')
            this.loadingtext = '无匹配数据'
            if (this.inRoles('ROLE_shhadmin') || this.inRoles('ROLE_admin')) {
              this.deptlist = response.data.result.result
            } else {
              this.deptlist = response.data.result.result.filter(item => {
                let flag = false
                if (JSON.parse(localStorage.getItem('type1')) && item.unitName === '机关司局') {
                  flag = true
                }
                if (JSON.parse(localStorage.getItem('type2')) && item.unitName === '派出机构') {
                  flag = true
                }
                if (JSON.parse(localStorage.getItem('type3')) && item.unitName === '直属单位') {
                  flag = true
                }
                return flag
              })
            }
            this.deptlist.forEach(item => {
              if (item.children.filter(it => it.zhiliangpinggu).length > 0) {
                this.canExport = true
              }
            })
            this.TheYear = response.data.result.year
            this.shenghuohuiName = response.data.result.name
            this.canCreate = response.data.result.canCreate
            this.status = response.data.result.status
            this.pingguFiles = response.data.result.pingguFiles
            if (response.data.canCreate === true && (this.inRoles('ROLE_shhadmin') || this.inRoles('ROLE_admin'))) {
              this.startBtnsVisible = true
            }
            console.log('获取总数:' + response.data.message)
            console.log('获取size:' + this.pagenum)
            this.totalnum = parseInt(response.data.message)
          } else {
            console.log('获取失败:' + response.data.message)
            this.$message({
              message: '获取失败:' + response.data.message,
              type: 'error'
            })
          }
        })
        .catch(error => {
          console.log(error)
          this.$message({
            message: '获取失败:' + error,
            type: 'error'
          })
        })
    },
    handleStart () {
      this.startLoading = true
      this.$http.post(this.$http.defaults.shenghuohuiAPI + `api/newFlow/saveStart?`, {shenghuohuiId: this.$route.params.id}).then(response => {
        console.log(response.data.success)
        if (response.data.success === true) {
          this.$message({
            message: '启动成功',
            type: 'success'
          })
          this.startLoading = false
          this.getDept()
        } else {
          this.$message({
            message: '启动失败:' + response.data.message,
            type: 'error'
          })
          this.startLoading = false
        }
      }).catch(error => {
        console.log(error)
        this.$message({
          message: '启动失败:' + error,
          type: 'error'
        })
        this.startLoading = false
      })
    },
    exportexcelfujian: function () {
      window.open(this.$http.defaults.baseURL + this.$http.defaults.shenghuohuiAPI + `api/shenghuohuiunit/getShenghuohuiPingguFiles?shenghuohuiId=` + this.$route.params.id)
    },
    exportexcel: function () {
      window.open(this.$http.defaults.baseURL + this.$http.defaults.shenghuohuiAPI + `api/shenghuohui2020/download?shhId=` + this.$route.params.id)
    },
    exportexcelnew: function () {
      window.open(this.$http.defaults.baseURL + this.$http.defaults.shenghuohuiAPI + `api/newFlow/exportUnits?shenghuohuiId=` + this.$route.params.id)
    },
    tableresize (obj) {
      var clientHeight = 0
      if (document.body.clientHeight && document.documentElement.clientHeight) {
        clientHeight = (document.body.clientHeight < document.documentElement.clientHeight) ? document.body.clientHeight : document.documentElement.clientHeight
      } else {
        clientHeight = (document.body.clientHeight > document.documentElement.clientHeight) ? document.body.clientHeight : document.documentElement.clientHeight
      }
      obj.$nextTick(function () {
        obj.tableHeight = clientHeight - 172
      })
    }
  },
  mounted () {
    this.getDept()
    this.shhAuth = localStorage.getItem('shhAuth')
    this.tableresize(this)
    window.onresize = () => {
      // 通过捕获系统的onresize事件触发我们需要执行的事件
      this.tableresize(this)
    }
  }
}
</script>
<style scoped>
#Shenghuohui{
  padding: 0
}
</style>
<style>
#shenghuohuiDetail .el-table .row-b{
  font-weight:bolder
}
#listtree i{
  padding-right:5px;
}
i.icon-wenjianjia1{
  color:#ffc500 !important;
}
i.icon-cf-c24{
  color:#1296db !important;
}
i.icon-danwei{
  color:#6fb400 !important;
}
#listtree {
  clear: both;
  height:100%;
  margin-top:0;
  overflow: hidden;
}
#listtree .el-tree-node__content{
  height:50px;
}
#listtree .nodelist{
  font-size:var(--size) !important;
  line-height: 50px;
}
#listtree .nodelist .el-progress {
  padding:15px 0 0;
}
#listtree .el-tree{
  background: #fff;
}
 #shenghuohuiDetail .wboxd{
    padding:10px;
    width: calc(100% - 20px);
    background: #fff;
    border: 1px solid #95B8E7;
    margin:0 10px;
    overflow: hidden;
  }
</style>
